using System;
using System.Text;
using UnityEngine;
using System.Collections;
using System.Threading;
public class Rms {
    public static int status; // 0: nothing, 1: working, 2: waitingSave, 3: waitingLoad
    public static sbyte[] data;
    public static string filename;
    const int INTERVAL = 5;
    const int MAXTIME = 500;
    public static void saveRMS(string filename, sbyte[] data)
    {
        if (Thread.CurrentThread.Name == Main.mainThreadName)
            __saveRMS(filename, data);
        else
            _saveRMS(filename, data);
    }
    public static sbyte[] loadRMS(string filename)
    {
        if (Thread.CurrentThread.Name == Main.mainThreadName)
            return __loadRMS(filename);
        else
            return _loadRMS(filename);
    }

    public static string loadRMSString(string fileName)
    {
        sbyte[] data = Rms.loadRMS(fileName);
        if (data == null)
            return null;
        DataInputStream dis = new DataInputStream(data);
        try
        {
            string t = dis.readUTF();
            dis.close();
            return t;
        }
        catch (Exception e)
        {
            Cout.println(e.StackTrace);
        }
        return null;
    }
    public static byte[] convertSbyteToByte(sbyte[] var)
    {
        byte[] temp = new byte[var.Length];
        for (int i = 0; i < var.Length; i++)
        {
            if (var[i] > 0)
                temp[i] = (byte)var[i];

            else temp[i] = (byte)(var[i] + 256);
        }

        return temp;
    }
    public static void saveRMSString(string filename, string data)
    {

        DataOutputStream dos = new DataOutputStream();
        try
        {
            dos.writeUTF(data);
            Rms.saveRMS(filename, dos.toByteArray());
            dos.close();
        }
        catch (Exception e)
        {
            Cout.println(e.StackTrace);
        }
    }

    private static void _saveRMS(string filename, sbyte[] data)
    {
        if (Rms.status != 0)
        {
            Debug.LogError("Cannot save RMS " + filename + " because current is saving " + Rms.filename);
            return;
        }
        Rms.filename = filename;
        Rms.data = data;
        status = 2; // waiting save
        int i = 0;
        while (i < MAXTIME)
        {
            Thread.Sleep(INTERVAL);
            if (status == 0) break; //save done
            i++;
        }
        if (i == MAXTIME) Debug.LogError("TOO LONG TO SAVE RMS " + filename);
        //else Debug.Log("Save RMS done: "+filename+" in "+(i*5)+"ms");
    }
    private static sbyte[] _loadRMS(string filename)
    {
        if (Rms.status != 0)
        {
            Debug.LogError("Cannot load RMS " + filename + " because current is loading " + Rms.filename);
            return null;
        }
        Rms.filename = filename;
        Rms.data = null;
        status = 3; // waiting load
        int i = 0;
        while (i < MAXTIME)
        {
            Thread.Sleep(INTERVAL);
            if (status == 0) break; //load done
            i++;
        }
        if (i == MAXTIME) Debug.LogError("TOO LONG TO LOAD RMS " + filename);
        //else Debug.Log("Load RMS done: "+filename+ " in "+(i*5)+"ms");
        return Rms.data;
    }

    // Call this in Main.update();
    public static void update()
    {
        if (Rms.status == 2)
        {
            Rms.status = 1;
            __saveRMS(Rms.filename, Rms.data);
            Rms.status = 0;
        }
        else if (Rms.status == 3)
        {
            Rms.status = 1;
            Rms.data = __loadRMS(Rms.filename);
            Rms.status = 0;
        }
    }

    public static int loadRMSInt(String file)
    {
        sbyte[] b = loadRMS(file);
        return b == null ? -1 : (int)b[0];
    }
    public static void saveRMSInt(String file, int x)
    {
        try
        {
            saveRMS(file, new sbyte[] { (sbyte)x });
        }
        catch (Exception e)
        {
        }
    }
    private static void __saveRMS(string filename, sbyte[] data)
    {
        string d = ByteArrayToString(ArrayCast.cast(data));
        //  Debug.Log("SAVE RMS " + filename + " --> " + data.Length + " --> " + d);
        PlayerPrefs.SetString(filename, d);

    }
    private static sbyte[] __loadRMS(string filename)
    {
        string d = PlayerPrefs.GetString(filename);
        byte[] data;
        try
        {
            data = StringToByteArray(d);
        }
        catch (Exception e)
        {
            Debug.LogError("PARSE RMS STRING FAIL " + e.StackTrace);
            return null;
        }
        // Debug.Log("LOAD RMS " + filename + " --> size=" + data.Length + " --> d=" + d);
        if (data.Length == 0) return null;
        return ArrayCast.cast(data);
    }
    public static void deleteAll()
    {
        Debug.LogWarning("ALL RMS CLEAR");
        PlayerPrefs.DeleteAll();
    }
    public static string ByteArrayToString(byte[] ba)
    {
        string hex = BitConverter.ToString(ba);
        return hex.Replace("-", "");
    }

    public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;
    }
    public static void deleteRecord(string name)
    {
        try
        {
            PlayerPrefs.DeleteKey(name);
        }
        catch (Exception e)
        {
            //			e.printStackTrace();
            Cout.println("loi xoa RMS --------------------------" + e.ToString());
        }
    }
    public static void clearRMS()
    {
        deleteRecord("data");
        deleteRecord("dataVersion");
        deleteRecord("map");
        deleteRecord("mapVersion");
        deleteRecord("skill");
        deleteRecord("killVersion");
        deleteRecord("item");
        deleteRecord("itemVersion");
    }

    public static void saveIP(string strID)
    {
        saveRMSString("NJIP", strID);
    }

}

